import java.util.LinkedList;
import java.util.Queue;

class Solution {

    int[] dx = {1,-1,0,0};
    int[] dy = {0,0,1,-1};
    boolean[][] visited;
    int m;
    int n;
    int ret;

    public int maxAreaOfIsland(int[][] grid) {
        m = grid.length;
        n = grid[0].length;
        visited = new boolean[m][n];
        // 针对每个位置都进行一次BFS
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1 && !visited[i][j]) {
                    bfs(grid, i, j);
                }
            }
        }
        return ret;
    }

    private void bfs(int[][] grid, int i, int j) {
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{i, j});
        visited[i][j] = true;
        int count = 1; // 统计'1'的数量
        while (!queue.isEmpty()) {
            int[] arr = queue.poll();
            for (int k = 0; k < 4; k++) {
                int sr = arr[0] + dx[k], sc = arr[1] + dy[k];
                // 判断 越界、岛屿、访问过
                if (sr >= 0 && sr < m && sc >= 0 && sc < n && grid[sr][sc] == 1 && !visited[sr][sc]) {
                    queue.offer(new int[]{sr, sc});
                    visited[sr][sc] = true;
                    count++;
                }
            }
        }
        ret = Math.max(count, ret); // 更新最大值
    }
}